<template>
    <el-card class="container">
        <el-row type="flex" justify="space-between" align="middle" class="custom-banner">
            <el-button v-if="tableData.length !== 0" @click="delPageData" style="margin-bottom: 10px;" plain
                type="danger">删除该表数据</el-button>
            <div class="header">
                <div style="float: left; display: flex; width: 20%;">
                    <img style=" width: 20%; height: 20%;" src="/public/paperAnalysis.png" alt="">
                    <span>试卷分析</span>
                </div>
                <div style="float: right;display: flex;width: 20%;">
                    <img style=" width: 20%; height: 20%;" src="/public/teacher.png" alt="">
                    <span>教师：钟秀玉</span>
                </div>
                <div style="float: right;display: flex;width: 20%;">
                    <img style="   width: 20%; height: 20%;" src="/public/course.png" alt="">
                    <span>课程：数据结构</span>
                </div>
                <div style="float: right;display: flex;width: 20%;">
                    <img style="   width: 20%; height: 20%;" src="/public/class.png" alt="">
                    <span>班级：2203</span>
                </div>
                <div style="float: right;display: flex;width: 20%;">
                    <img style="  width: 20%; height: 20%;" src="/public/academy.png" alt="">
                    <span>学院：计算机学院</span>
                </div>
            </div>
        </el-row>
        <div class="width:100%">
            <!-- <el-table :spanMethod="spanMethod" v-if="tableData.length" :data="tableData" stripe style="width: 100%"
                border="vertical">
                <el-table-column v-for="header in headers" :key="header" :prop="header"
                    :label="header"></el-table-column>
            </el-table> -->
            <div class="table-container">
                <table v-if="tableData.length" class="responsive-table" border="1">
                    <thead>
                        <tr style="background-color: #f2f2f2;">
                            <th v-for="header in headers" :key="header">{{ header }}</th>
                        </tr>
                    </thead>
                    <tbody>
                        <template v-for="(row, rowIndex) in processedTableData" :key="rowIndex">
                            <tr>
                                <td v-for="(cell, cellIndex) in row" :key="cellIndex" :colspan="cell.colspan"
                                    :rowspan="cell.rowspan">
                                    {{ cell.value }}
                                </td>
                            </tr>
                        </template>
                    </tbody>
                </table>
            </div>





        </div>
        <el-card class="chartsGroup">
            <template v-if="tableData.length" #default>
                <div class="chartsStyle">
                    <div>
                        <Horizontal_columnChart></Horizontal_columnChart>
                    </div>
                    <div>
                        <basicColumnChart></basicColumnChart>
                    </div>
                    <div style="margin-top: 20px;">
                        <pieWithGap></pieWithGap>
                    </div>
                </div>
            </template>
            <el-card>
                <div style="display: flex; justify-content: space-around;height: 70vh;">
                    <div class="leftBox">
                        <p style="color: red;font-style: italic;font-size: 35px;word-break: break-all;">
                            请下载模板，根据模板填写好分数后再上传分数!
                        </p>
                        <el-card style="width: 100%;">
                            <h1 style="height: 5%;font-size: 40px; text-align: center;">下载模板</h1>
                            <div class="btGroup_1"
                                style="height: 10vh; display: flex; justify-content: space-around;align-items: center;">
                                <el-button style="font-size: 30px;border: none;"
                                    @click="getExcelTable('A')">下载A卷模板</el-button>
                                <el-button style="font-size: 30px;border: none;" size="large"
                                    @click="getExcelTable('B')">下载B卷模板</el-button>
                            </div>
                        </el-card>
                    </div>
                    <el-card style="width: 50%; height: 100%;">
                        <h1 style="font-size: 40px; text-align: center;">上传文件</h1>
                        <Analysis_Implement @updateData="handleUpdateData" />
                    </el-card>
                </div>
            </el-card>
        </el-card>
    </el-card>
</template>
<script setup>
import { ref, onMounted, watch } from 'vue';
import { ElTable, ElTableColumn } from 'element-plus';
import Analysis_Implement from './Analysis_Implement.vue'
import pieWithGap from '@/components/pieWithGap.vue'
import Horizontal_columnChart from '@/components/Horizontal_columnChart.vue'
import { autoMakeXlsx_api } from '@/api/target_item_info_input'
const tableData = ref([]);
const headers = ref([]);
import eventBus from '/eventBus';
import basicColumnChart from '@/components/basicColumnChart.vue'
// 组件挂载时尝试从LocalStorage加载数据
const processedTableData = ref([]); // 处理后的表格数据
onMounted(() => {
    loadFromLocalStorage();
});

// 将对象的最后 count 个键值对移动到对象的最前方
function moveLastToFirst(obj, count) {
    const keys = Object.keys(obj);
    const lastKeys = keys.slice(-count); // 获取最后 count 个键
    // console.log("lastKeys", lastKeys);
    const newKeys = lastKeys.concat(keys.slice(0, -count)); // 合并最后 count 个键和剩余的键
    // console.log("newKeys", newKeys);
    const newObj = {};
    let myMap = new Map();
    newKeys.forEach(key => {
        // console.log("key", key);
        // newObj[key] = obj[key];
        myMap.set(key, obj[key]);
        // obj[key]=== obj.key
        // console.log("newObj[key]", newObj[key]);
        // console.log("newObj", newObj);
    });
    // console.log("myMap", myMap);
    return myMap;
}

// 将表格数据数组中的每个对象的最后 count 个键值对移动到最前方
function moveLastKeysToFirst(tableData, count) {
    tableData.forEach(obj => {
        // console.log("obj", obj);
        let movedMap = new Map();
        movedMap = moveLastToFirst(obj, count);
        Object.assign(obj, movedMap);
        // 将一个至多个源对象上的可枚举属性（enumerable）拷贝到目标对象上，并将目标对象返回
    });
}

const processTableData = () => {
    const processedData = [];
    moveLastKeysToFirst(tableData.value.slice(0, 2), 10);
    // console.log("tableData.value", tableData.value);
    tableData.value.forEach((row, rowIndex) => {
        const processedRow = [];
        // 对每一个row行的键遍历
        // console.log("rowIndex", rowIndex);
        Object.keys(row).forEach((key, cellIndex) => {
            // key是键，cellindex就是键的索引，row[key]是键的值
            // console.log(key, cellIndex, row[key]);
            const cell = row[key];
            // 检查单元格是否为空
            if (cell !== '') {
                let rowspan = 1;
                let colspan = 1;
                // 计算 colspan
                for (let i = cellIndex + 1; i < Object.keys(row).length; i++) {
                    if (row[Object.keys(row)[i]] === '') {
                        colspan++;
                    } else {
                        break;
                    }
                }
                // 计算 rowspan
                // for (let i = rowIndex + 1; i < tableData.value.length; i++) {
                //     if (tableData.value[i][key] === '') {
                //         rowspan++;
                //     } else {
                //         break;
                //     }
                // }
                // console.log("{ value: cell, rowspan, colspan }", { value: cell, rowspan, colspan });
                processedRow.push({ value: cell, rowspan, colspan });
            }
        });
        processedData.push(processedRow);
    });
    processedTableData.value = processedData;
    // console.log("processedTableData.value", processedTableData.value);
};


watch(tableData, processTableData); // 监听表格数据变化
onMounted(processTableData); // 初始化时处理表格数据
import { useRoute } from 'vue-router';
const route = useRoute();
const subId = parseInt(route.params.subId);
const getExcelTable = async (paperType) => {
    try {
        const response = await autoMakeXlsx_api(paperType, subId);
        // 提取buffer数据
        const buffer = response.data.content.data;

        // 创建Blob对象
        const blob = new Blob([new Uint8Array(buffer)], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' });

        // 创建一个URL链接，指向响应体的blob
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        // 从响应头中提取文件名，或者如果没有则指定默认的文件名
        const contentDisposition = response.headers['content-disposition'];
        // let filename = 'output.xlsx';
        let filename = `${paperType}卷模板.xlsx`;
        if (contentDisposition) {
            const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
            const matches = filenameRegex.exec(contentDisposition);
            if (matches != null && matches[1]) {
                filename = matches[1].replace(/['"]/g, '');
            }
        }
        link.setAttribute('download', filename);

        // 触发下载
        // document.body.appendChild(link);
        // link.click();

        // 清理
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
    } catch (error) {
        console.error('下载Excel文件失败:', error);
    }
}
// 处理文件上传
// const handleFileUpload = (event) => {
//     const file = event.target.files[0];
//     if (!file) return;

//     const reader = new FileReader();
//     reader.onload = (e) => {
//         const arrayBuffer = e.target.result;
//         const data = new Uint8Array(arrayBuffer);
//         const workbook = XLSX.read(data, { type: 'array' });
//         const sheetName = workbook.SheetNames[0];
//         const sheet = workbook.Sheets[sheetName];
//         const json = XLSX.utils.sheet_to_json(sheet, { header: 1 });
//         headers.value = json[2];
//         const regularData = json.slice(3).map(row => {
//             const rowData = {};
//             row.forEach((cell, index) => rowData[headers.value[index]] = cell);
//             return rowData;
//         });
//         const specialData = json.slice(0, 2).map(row => {
//             const specialRowData = {};
//             headers.value.forEach((header, index) => specialRowData[header] = row[index] || '');
//             return specialRowData;
//         });
//         tableData.value = specialData.concat(regularData);

//         // 将数据保存到LocalStorage
//         saveToLocalStorage();
//     };
//     reader.readAsArrayBuffer(file);
// };
const handleUpdateData = (json) => {
    headers.value = json[2];
    // const regularData = json.slice(3).map(row => {
    //     const rowData = {};
    //     row.forEach((cell, index) => rowData[headers.value[index]] = cell);
    //     console.log("rowData", rowData);
    //     return rowData;
    // });
    const regularData = json.slice(3).map(row => {
        const rowData = new Map();
        row.forEach((cell, index) => rowData.set(headers.value[index], cell));
        return rowData;
    });
    // const specialData = json.slice(0, 2).map(row => {
    //     const specialRowData = {};
    //     headers.value.forEach((header, index) => specialRowData[header] = row[index] || '');
    //     return specialRowData;
    // });
    const specialData = json.slice(0, 2).map(row => {
        const specialRowData = new Map();
        headers.value.forEach((header, index) => specialRowData.set(header, row[index] || ''));
        return specialRowData;
    });
    
    tableData.value = specialData.concat(regularData);
    console.log("tableData.value_kzy", tableData.value);
    // 保存数据到 LocalStorage
    saveToLocalStorage();
};
const delPageData = () => {
    localStorage.removeItem('uploadedData');
    eventBus.methods.clearLocalStorage()
    location.reload(true);
}
// 保存数据到LocalStorage
const saveToLocalStorage = () => {
    console.log("tableData.value_saveToLocalStorage", tableData.value);
    let myMap = new Map();
    const dataToStore = {
        headers: headers.value,
        tableData: tableData.value
    };
    myMap.set('headers', headers.value);
    myMap.set('tableData', tableData.value);
    console.log("myMap", myMap);
    // 将 Map 对象转换为字符串，并存储到 LocalStorage 中
    // localStorage.setItem('myMap', JSON.stringify(Array.from(myMap.entries())));
    // 从 LocalStorage 中获取字符串，并将其转换为 Map 对象
    // let storedMap = new Map(JSON.parse(localStorage.getItem('myMap')));
    // localStorage.setItem('uploadedData', JSON.stringify(dataToStore));
    localStorage.setItem('uploadedData', JSON.stringify(Array.from(myMap.entries())));
};
// 从LocalStorage加载数据
const loadFromLocalStorage = () => {
    const storedData = localStorage.getItem('uploadedData');
    if (storedData) {
        const { headers: storedHeaders, tableData: storedTableData } = JSON.parse(storedData);
        headers.value = storedHeaders;
        tableData.value = storedTableData;
    }
};

</script>

<style lang="scss" scoped>
$table-max-height: 400px; // 表格容器的最大高度

.table-container {
    max-height: $table-max-height;
    overflow-x: auto; // 水平滚动条
    position: relative; // 使得固定列相对于容器定位

    .responsive-table {
        width: auto; // 取消 100% 宽度
        border-collapse: collapse;

        th,
        td {
            padding: 8px;
            border: 1px solid #ddd;
            white-space: nowrap; // 避免内容换行
            overflow: hidden; // 内容溢出隐藏
            text-overflow: ellipsis; // 内容溢出时显示省略号
        }
    }
}

table {
    border-collapse: collapse;
    margin: 25px 0;
    font-size: 0.9em;
    font-family: sans-serif;
    min-width: 400px;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.15);
}

th,
td {
    // border: 1px solid black;
    // padding: 8px;
    text-align: center;
    padding: 12px 15px;
    border: 1px solid #dddddd;
}

th {
    background-color: #009879;
    color: #ffffff;
}

tr:hover {
    background-color: #f3f3f3;
}

.wide {
    width: 320px;
}

.container {
    // max-width: 2500px;
    max-width: 100%;

    .custom-banner {
        color: white;
        margin-bottom: 20px;

        .header {
            width: 100%;
            background-color: rgba(95, 214, 217, 0.5);
            background-color: #d9e8fc;
            // background-color: #e5f5fe;
            color: #64748b;
            text-align: center;
            height: 10vh;
            // justify-content: center;
            display: flex;
            // line-height: 100px;
            align-items: center;
            // font-size: 16px;
            // font-size: $global-font-size;
            font-family: Arial, sans-serif;
            border-radius: 5px;
            border-left: 5px solid #60a5fa;
            border-top: none;
            border-right: none;
            border-bottom: none;
            margin-bottom: 10px;
            padding-right: 20px;

            span {
                display: flex;
                // height: 10px;
                // line-height: 10px;
                align-items: center;
            }
        }
    }

    .chartsGroup {
        // margin-top: 30px;
        background-color: #d9e8fc;
        border: 3px solid #60a5fa;

        .chartsStyle {
            overflow-x: auto;
            // max-width: 3000px;
            width: 100%;
            display: flex;
            flex-direction: column;
            justify-content: space-around;
            align-items: center;
            // .leftChart{
            //     display: flex;
            //     flex-direction: column;
            //     align-items: center;
            //     justify-content: space-around;
            // }
            // ::v-deep .el-card:nth-child(1) {
            //     background-color: white;
            //     display: flex;
            //     justify-content: center;
            //     align-items: center;
            //     width: 300px;
            //     box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            // }
            // ::v-deep .el-card:nth-child(2){
            //     background-color: white;
            //     display: flex;
            //     justify-content: center;
            //     align-items: center;
            //     width: 700px;
            //     height: 450px;
            // }
        }
    }

    ::v-deep .el-table {
        background-color: #e5f5fe;
        padding: 5px;

        .el-table__cell {
            background-color: #d9e8fc;
        }

        .el-table__th {
            background-color: #075ac7;
        }
    }
}
</style>
